package kr.co.creativeideas.gooq.view;

import kr.co.creativeideas.gooq.activity.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class TouchShapeView extends View {

	private static final int STROKE_WIDTH = 5;
	private static final int CIRCLE_RADIUS = 80;
	private Paint drawingPaint = null;
	private boolean isTouch = false;
	private int pathEffectPhase = 0;
	private PointF mPointF;

	public TouchShapeView(Context context) {
		super(context);
		initialize(context);
	}

	public TouchShapeView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initialize(context);
	}

	public TouchShapeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initialize(context);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if(isTouch) {
			DashPathEffect effect = new DashPathEffect(new float[] { 7, 7 },pathEffectPhase);
			drawingPaint.setPathEffect(effect);
			canvas.drawCircle(mPointF.x, mPointF.y, CIRCLE_RADIUS,drawingPaint);
			++pathEffectPhase;
			invalidate();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		super.onTouchEvent(event);
		int action = event.getAction() & MotionEvent.ACTION_MASK;
		switch (action) {
		case MotionEvent.ACTION_DOWN: 
			isTouch = true;
			setPoints(event);
			invalidate();
			break;
		
		case MotionEvent.ACTION_UP: 
			isTouch = false;
			break;
		
		case MotionEvent.ACTION_MOVE: 
			if (isTouch) {
				setPoints(event);
				invalidate();
			}
			break;

		}
		return true;
	}

	private void initialize(Context context) {		
		BitmapDrawable bgImage = (BitmapDrawable)getResources().getDrawable(R.drawable.tiled);
		bgImage.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
		setBackgroundDrawable(bgImage);
		
		drawingPaint = new Paint();
		drawingPaint.setColor(Color.RED);
		drawingPaint.setStrokeWidth(STROKE_WIDTH);		
		drawingPaint.setStyle(Paint.Style.FILL_AND_STROKE);
		drawingPaint.setAntiAlias(true);		
		mPointF = new PointF();
	}

	public void setPoints(MotionEvent event) {		
		mPointF.set(event.getX(), event.getY());
	}
}
